package com.xuesi.demoadmin.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.xuesi.demoadmin.entity.Permission;
import com.xuesi.demoadmin.entity.User;
import com.xuesi.demoadmin.mapper.PermissionMapper;
import com.xuesi.demoadmin.service.IPermissionService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private TokenServiceImpl tokenServiceImpl;

    @Autowired
    private PermissionMapper permissionMapper;

    public boolean checkPermission(String token, String requestUri) {
        User user = this.tokenServiceImpl.decode(token);
        Long userId = user.getUserId();

        List<Permission> permissionList = this.selectPermissionListByUserId(userId);
        Set<String> permissionSet = new HashSet<>();
        for (Permission permission : permissionList) {
            String path = permission.getPath();
            if (path != null && !path.equals("")) {
                permissionSet.add(path);
            }
        }

        boolean isContains = permissionSet.contains(requestUri);
        return isContains;
    }

    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public List<Permission> selectPermissionListByUserId(Long userId) {
        return this.permissionMapper.selectPermissionListByUserId(userId);
    }

    /**
     * 查询权限列表
     * 
     * @param permission 权限信息
     * @return 权限列表
     */
    @Override
    public List<Permission> selectPermissionList(Permission permission) {
        return this.permissionMapper.selectPermissionList(permission);
    }
}
